
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { View, StyleSheet, TouchableOpacity, Text, FlatList, Image, Animated } from "react-native";
import {Popup, Toast, Utils, TopBar} from 'tuya-panel-kit';
import TYSdk from '../../api';
import dpCodes from '../../config/dpCodes';
import Strings from '../../i18n';
import Res from '../../res';
import { debounce } from '../../utils';

import { commonApi } from '@tuya/tuya-panel-api';



const { parseHour12, parseTimer, stringToSecond } = Utils.TimeUtils;
const { trigger_status: trigger_statusCode, no_reminder_status: no_reminder_statusCode } = dpCodes;


class FeedTimerEditScene extends Component {
  static defaultProps = {
    dpState: {},
  };

  constructor(props) {
    super(props);
    this.state = {
      devID: null,
      devType: '0',
      startTimeStr: null,
      endTimeStr: null,
      startTimeMin: null,
      endTimeMin: null,
      count: 1,
      timerCloseSwitch: false,
      repeatChoose: '1',
      weekChoose: null,
      weekBinaryString: '0000000',
      weekdayString: Strings.repeat_value_only_once,// 默认执行一次
      showToast: false,
      toastTips: '',
      timerStringArr: [],
      showTop: true,
    };
  }

  async componentDidMount() {
    try {

      TYSdk.device.getDeviceInfo().then(res => {
        const { devId, groupId } = res;
        this.setState({
          devID: groupId || devId,
          devType: groupId ? '1' : '0',
        });
      });

      const { timerList, timer, isEditTimer } = this.props;
      // console.log('timerList', timerList);

      // 编辑定时 还原数据
      if (isEditTimer) {
        const weekBinaryString = timer.loops;
        const weekdayString = TYSdk.changeToWeekdays(timer.loops);
        const startTimeStr = timer.endTime == null ? timer.time : `${timer.time} ~ ${timer.endTime}`;
        const name = TYSdk.timerName(timer.aliasName);
        let repeatChoose;
        if (weekBinaryString === '0000000'){
          repeatChoose = '1';
        }else if(weekBinaryString === '1111111'){
          repeatChoose = '2';
        }else {
          repeatChoose = '3';
        }
        const startTimeMin = stringToSecond(startTimeStr);

        const dps = TYSdk.jsonToDict(timer.dps);
        const count = dps['141'];

        this.setState({
          weekBinaryString, weekdayString, startTimeStr, repeatChoose, startTimeMin, count
        });

      }

      let timerStringArr = [];
      timerList.forEach((item) => {
        // console.log('item', item);
        timerStringArr.push(item.timerString);
      })
      this.setState({ timerStringArr });
      // console.log('timerStringArr', timerStringArr);

    } catch (err) {
      console.warn(err);
    }
  }


  addClick = debounce(() => {

    const { devID, devType, count, startTimeStr, weekBinaryString, timerStringArr } = this.state;
    const { isEditTimer, timer } = this.props;

    let result = '';
    let resultCheck = '';
    let isMissPara;

    let tips = '';
    if (weekBinaryString == null || weekBinaryString === ''){
      isMissPara = true;
      tips = '请选择重复周期';
    }


    result = '[{"dps":{"141":'+count+'},"time":"'+startTimeStr+'"}]';
    resultCheck = result;
    if (isEditTimer){
      // result = '[{"dps":{"141":'+count+'},"time":"'+startTimeStr+'","timerId":"$VAR:timerIdArray['+timer.id+']"}]';
      result = '[{"dps":{"141":'+count+'},"time":"'+startTimeStr+'","timerId":"'+timer.id+'"}]';
    }

    if (startTimeStr == null || startTimeStr === ''){
      isMissPara = true;
      tips = '请选择时间';
    }

    console.log('动作actionsArray',result)
    if (isMissPara){
      // 缺少参数，不提示直接禁用按钮
      // 没有翻译文本，缺少条件直接返回不响应，不提示
      // this.setState({showToast: true, toastTips: tips});
      return;
    }

    const timerString = weekBinaryString+resultCheck;
    // console.log('timerString ',timerString);

    if (timerStringArr.includes(timerString)) {
      tips = '该定时器已存在，请重新修改';
      this.setState({showToast: true, toastTips: tips});
      return;
    }



    this.setState({showToast: false, toastTips: ''});

    // 喂食定时-1份
    const name = Strings.feeder_timer_title + '-' + Strings.formatValue('dialog_option_feed_count', count);

    if (isEditTimer) {
      commonApi.timerApi
        .modifyGroupTimer({
          bizId: devID, // 根据 getDevInfo 判断是否存在 groupId。若存在，则为群组设备，否则为单设备
          bizType: devType,
          loops: weekBinaryString,
          // category: 'feed', // 分类类别可自行定义，需要与查询定时列表的 category 保持一致
          status: 1, // 当前定时状态是否开启
          // 用户设置的在多个时间点、dp 点需要执行的状态或者事件。
          actionsArray: result,
          isAppPush: true,
          aliasName: name,//count+'份',
        })
        .then(response => {
          console.log(response);
          this.props.isNeedRefresh(true);// 通知定时列表页面刷新数据
          TYSdk.Navigator.pop();
        })
        .catch();
    }else {
      commonApi.timerApi
        .addGroupTimer({
          bizId: devID, // 根据 getDevInfo 判断是否存在 groupId。若存在，则为群组设备，否则为单设备
          bizType: devType,
          loops: weekBinaryString,
          category: 'feed', // 分类类别可自行定义，需要与查询定时列表的 category 保持一致
          status: 1, // 当前定时状态是否开启
          // 用户设置的在多个时间点、dp 点需要执行的状态或者事件。
          actionsArray: result,
          isAppPush: true,
          aliasName: name,//count+'份',
        })
        .then(response => {
          console.log('modifyGroupTimer response',response);
          this.props.isNeedRefresh(true);// 通知定时列表页面刷新数据
          TYSdk.Navigator.pop();
        })
        .catch();
    }

  });

  modePopupClicked = debounce(v => {
    const { count } = this.state;

    Popup.list({
      type: 'radio',
      contentCenter: true, // 内容是否居中
      titleTextStyle: { fontSize: 16, fontWeight: 'bold' },
      styles: { title: { fontSize: 16, fontWeight: 'bold' } },
      // cancelTextStyle: { width: 100, height: 40, borderRadius: 20, textAlign: 'center', backgroundColor: '#afd8ea' },
      confirmTextStyle: { fontSize: 16, fontWeight: 'bold', color: '#22a8dc' },
      iconTintColor: '#22a8dc',
      maxItemNum: 7,
      dataSource: [
        {
          key: '1',
          title: Strings.formatValue('dialog_option_feed_count', 1),//'1份',
          value: 1,
        },
        {
          key: '2',
          title: Strings.formatValue('dialog_option_feed_count', 2),//'2份',
          value: 2,
        },
        {
          key: '3',
          title: Strings.formatValue('dialog_option_feed_count', 3),//'3份',
          value: 3,
        },
      ],
      title: Strings.dialog_title_feed_count,//'份数',
      cancelText: Strings.cancel,//'取消',
      confirmText: Strings.ok,//'确认',
      value: count,
      onMaskPress: ({ close }) => close(),
      onSelect: (value, { close }) => {
        // setState({ listValue: value });
      },
      onConfirm: (value, { close }) => {
        this.setState({ count: value });
        close();
      },
    });
  });

  repeatPopupClicked = debounce(v => {
    const { repeatChoose, modeList } = this.state;
    // console.log('重复选项', repeatChoose);
    const repeatData = TYSdk.repeatData();

    Popup.list({
      type: 'radio',
      contentCenter: true, // 内容是否居中
      titleTextStyle: { fontSize: 16, fontWeight: 'bold' },
      styles: { title: { fontSize: 16, fontWeight: 'bold' } },
      // cancelTextStyle: { width: 100, height: 40, borderRadius: 20, textAlign: 'center', backgroundColor: '#afd8ea' },
      confirmTextStyle: { fontSize: 16, fontWeight: 'bold', color: '#22a8dc' },
      iconTintColor: '#22a8dc',
      // switchStyle: { confirmFontColor: '#22a8dc' },
      maxItemNum: 7,
      dataSource: repeatData,
      title: Strings.dialog_title_repeating_settings,//'重复选项',
      cancelText: Strings.cancel,//'取消',
      // confirmText: '确认',
      value: repeatChoose,
      footerType: 'singleCancel',
      onMaskPress: ({ close }) => close(),
      onSelect: (value, { close }) => {
        // console.log('重复选项结果', value);

        if (value === '1') {
          this.setState({ repeatChoose: value });
          this.setState({ weekdayString: Strings.repeat_value_only_once });// '执行一次'
          this.setState({ weekBinaryString: '0000000' });
          close();
        } else if (value === '2') {
          this.setState({ repeatChoose: value });
          this.setState({ weekdayString: Strings.repeat_value_everyday });// '每天'
          this.setState({ weekBinaryString: '1111111' });
          close();
        } else {
          close();
          // 延迟0.1秒执行
          setTimeout(() => {
            this.weekPopupClicked();
          }, 500);
        }

      },
      onConfirm: (value, { close }) => {
      },
    });
  });


  weekPopupClicked = debounce(v => {
    const { weekChoose } = this.state;
    // console.log('重复', weekChoose);
    const repeatWeekData = TYSdk.repeatWeekData();

    Popup.list({
      type: 'switch',
      contentCenter: true, // 内容是否居中
      titleTextStyle: { fontSize: 16, fontWeight: 'bold' },
      styles: { title: { fontSize: 16, fontWeight: 'bold' } },
      // cancelTextStyle: { width: 100, height: 40, borderRadius: 20, textAlign: 'center', backgroundColor: '#afd8ea' },
      confirmTextStyle: { fontSize: 16, fontWeight: 'bold', color: '#22a8dc' },
      iconTintColor: '#22a8dc',
      // switchStyle: { confirmFontColor: '#22a8dc' },
      maxItemNum: 7,
      dataSource: repeatWeekData,
      title: Strings.dialog_title_custom_repeat,// '自定义重复',
      cancelText: Strings.cancel,// '取消',
      confirmText: Strings.ok,//'确认',
      value: weekChoose,
      // footerType: 'singleCancel',
      onMaskPress: ({ close }) => close(),
      onSelect: (value, { close }) => {
        // setState({ listValue: value });
      },
      onConfirm: (value, { close }) => {
        if (value === null) {
          this.setState({ repeatChoose: '1' });
          this.setState({ weekdayString: Strings.repeat_value_only_once });// '执行一次'
          this.setState({ weekBinaryString: '0000000' });
        }else {
          this.setState({ repeatChoose: '3' });
          // console.log('重复选择结果', value);
          this.setState({ weekChoose: value });
          const binary = TYSdk.changeNumToBinaryWeek(value);
          // console.log('binary', binary);
          this.setState({ weekBinaryString: binary });
          const week = TYSdk.changeToWeekdays(binary);
          // console.log('week', week);
          this.setState({ weekdayString: week });
        }
        close();
      },
    });
  });

  timerPopupClicked = debounce(v => {
    // console.log('时间选择', v);
    const timemin = v === 1 ? this.state.startTimeMin : this.state.endTimeMin;
    const titleStr = v === 1 ? Strings.timer_on_time_title : Strings.timer_off_time_title;//'时间' : '关闭时间';
    Popup.timerPicker({
      title: titleStr,
      cancelText: Strings.cancel,//'取消',
      confirmText: Strings.ok,//'确认',
      confirmTextStyle: { fontSize: 16, fontWeight: 'bold', color: '#22a8dc' },
      startTime: timemin,
      // endTime: endTimeStr,
      is12Hours: false,
      singlePicker: true,
      symbol: '',
      onMaskPress: ({ close }) => close(),
      onConfirm: ({ startTime, endTime }, { close }) => {
        const time = parseTimer(startTime * 60);
        // console.log(startTime);
        // console.log('time', time);
        if (v === 1) {
          this.setState({ startTimeMin: startTime, startTimeStr: time });
        } else {
          this.setState({ endTimeMin: startTime, endTimeStr: time });
        }
        close();
      },
    });
  });

  toastView(tips, show){
    return(
        <Toast show={show} text={tips} onFinish={() => {
          this.setState( {showToast: false });
        }} />
    );
  }


  topView() {
    return (
      <TopBar.Container
        background="#FFFFFF"
        style={{ height: TopBar.height }}
        contentStyle={{ height: TopBar.height, marginTop: 10 }}
      >
        <TopBar.Action size={20} source={Res.fback} color="#4C4C4C" onPress={() => TYSdk.Navigator.pop()} />
        <TopBar.Content />
        <TopBar.Action
          source={Res.ftack}
          color="#4C4C4C"
          size={18}
          style={{marginTop:500}}
          onPress={() => {
            this.addClick();
          }}
        />
      </TopBar.Container>
    );
  }

  render() {
    const { showToast, toastTips, startTimeStr, count, weekdayString, showTop } = this.state;
    const { isEditTimer } = this.props;
    const title = isEditTimer ? Strings.page_title_edit : Strings.page_title_create_mode;


    return (
      <View style={[styles.container]}>
        {showTop ? this.topView() : null}
        <View
          style={{
            backgroundColor: '#FFFFFF',
            height: 100,
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          {/* 新建 */}
          <Text style={{ marginStart: 30, fontSize: 30, color: '#333333' }}>{ title }</Text>
          {/* <TouchableOpacity
            style={{ marginEnd: 5, marginTop: -1 }}
            onPress={() => {
              this.addClick();
            }}
          >
            <Image style={styles.tackIcon} source={Res.ftack} resizeMode="center" />
          </TouchableOpacity> */}
        </View>

        {/* 时间 */}
        <TouchableOpacity
          style={styles.cell}
          onPress={() => {
            this.timerPopupClicked(1);
          }}
        >
          <Text style={styles.cellTitle}>{Strings.timer_on_time_title}</Text>
          <View style={styles.rowBgView}>
            <Text style={[styles.subTitle, { marginLeft: 20 }]}>{startTimeStr}</Text>
            <Image style={styles.arrow} source={Res.enter} />
          </View>
        </TouchableOpacity>

        {/* 份数 */}
        <TouchableOpacity
          style={styles.cell}
          onPress={() => {
            this.modePopupClicked();
          }}>
          <Text style={styles.cellTitle}>{Strings.dialog_title_feed_count}</Text>
          <View style={styles.rowBgView}>
            <Text style={[styles.subTitle, { marginLeft: 20 }]}>{Strings.formatValue('dialog_option_feed_count',count)}</Text>
            <Image style={styles.arrow} source={Res.enter} />
          </View>
        </TouchableOpacity>


        {/* 重复 */}
        <TouchableOpacity
          style={styles.cell}
          onPress={() => {
            this.repeatPopupClicked();
          }}
        >
          <View style={styles.twoLines}>
            <Text style={styles.cellTitle}>{Strings.list_item_title_repeat}</Text>
            <Text style={[styles.subTitle, { marginTop: 5 }]}>{weekdayString}</Text>
          </View>
          <Image style={styles.arrow} source={Res.enter} />
        </TouchableOpacity>

        { showToast ? this.toastView(toastTips, showToast) : null }

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    alignSelf: 'stretch',
    // marginTop: -20,
  },
  cell: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: '#fff',
    height: 50,
    marginStart: 30,
    marginEnd: 10,
    marginTop: 10,
  },
  rowBgView: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  twoLines: {
    flexDirection: 'column',
    alignItems: 'stretch',
  },
  cellTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#000',
  },
  subTitle: {
    fontSize: 14,
    fontWeight: 'normal',
    color: '#757575FF',
  },
  tackIcon: {
    width: 60,
    height: 60,
  },
});

export default connect(({ dpState }) => ({
  dpState,
  trigger_status: dpState[trigger_statusCode],
  no_reminder_status: dpState[no_reminder_statusCode],
}))(FeedTimerEditScene);
